package com.joeshing.security.context;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.filter.GenericFilterBean;

import com.joeshing.security.context.CacheSecurityContextRepository.SaveToCacheResponseWrapper;

public class SaveSessionIdFilter extends GenericFilterBean {
	
	static final String FILTER_APPLIED = "__save_session_id_filter_applied";
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        SaveToCacheResponseWrapper response = (SaveToCacheResponseWrapper) res;

        if (request.getAttribute(FILTER_APPLIED) == null) {
        	response.saveSessionIdInCookie();
        	request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
        }
        try {
        	chain.doFilter(request, response);
        }finally{
        	request.removeAttribute(FILTER_APPLIED);
        }
	}


}
